<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible.sync="visible"
    width="800px"
    append-to-body
  >
    <el-form ref="form" :model="form" label-width="auto" :rules="rules">      

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name" class="person">
            <el-input
              v-model="form.name"
              placeholder="任务名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择">
              <el-option
                v-for="item in projects"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="题目" prop="questionId">
            <el-select v-model="form.questionId" filterable placeholder="请选择">
              <el-option
                v-for="item in questions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="任务状态" prop="status" class="person" v-if="this.type=== 'edit'">
            <el-radio-group v-model="form.status">
              <el-radio :label="'0'">未完成</el-radio>
              <el-radio :label="'1'">已完成</el-radio>
              <el-radio :label="'2'">审核通过</el-radio>
              <el-radio :label="'3'">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="选择训练员" prop="trainDoctorId">
            <el-select v-model="form.trainDoctorId" placeholder="请选择">
              <el-option
                v-for="item in trains"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="选择审核员" prop="reviewDoctorId">
            <el-select v-model="form.reviewDoctorId" placeholder="请选择">
              <el-option
                v-for="item in reviews"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="this.type=== 'edit'">
        <el-col :span="24">
          <el-form-item label="审核意见" prop="reviewRemark">
            <el-input
              v-model="form.reviewRemark"
              placeholder="审核意见"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="this.type=== 'edit'">
        <el-col :span="24">
          <el-form-item label="训练内容" prop="content">
            <el-input
              type="textarea"
              v-model="form.content"
              placeholder="训练内容"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="允许分享" prop="shared">
            <el-radio-group v-model="form.shared">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
import BindDialog from '@/components/bindDialog/index.vue'
import { dialogFrame } from './frameData'
import { modifyTask, addTask } from '@/api/trainTask'
import { getProjectList } from '@/api/trainProject';
import { getQuestionList } from '@/api/question';


const markForm = () => {
  return {
    name: '',
    projectId: '',
    questionId: '',
    status: '0',
    trainDoctorId: '',
    reviewDoctorId: '',
    reviewRemark: '',
    content: '',
    shared: 0
  }
}

export default {
  name: "",
  components: {
    BindDialog
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '任务名称是必填项', trigger: 'blur' }],
        projectId: [{ required: true, message: '项目是必填项', trigger: 'change' }],
        questionId: [{ required: true, message: '题目是必填项', trigger: 'change' }],
        status: [{ required: true, message: '任务状态是必填项', trigger: 'change' }],
        trainDoctorId: [{ required: true, message: '选择训练员是必填项', trigger: 'change' }],
        reviewDoctorId: [{ required: true, message: '选择审核员是必填项', trigger: 'change' }],
        content: [{ required: true, message: '训练内容是必填项', trigger: 'blur' }]
      },
      title: "",
      type: "",
      config: {
        edit: {
          func: modifyTask,
          title: "编辑"
        },
        new: {
          func: addTask,
          title: "新增"
        }
      },
      form: markForm(),
      visible: false,
      inputValue: "",
      inputVisible: false,
      dialogFrame,
      query: '',
      loading: false,
      projects: [],
      trains: [],
      reviews: [],
      questions: []
    };
  },
  watch: {
    'form.projectId': {
      handler(newVal) {
        const currentProject = this.projects.find(item => item.value === newVal);
        this.updateTrainsAndReviews(currentProject);
      },
      immediate: false
    }
  },
  mounted() {
    this.queryProject()
    this.queryQuestion()
  },
  methods: {
    updateTrainsAndReviews(currentProject){
      if (currentProject && currentProject.userList && currentProject.userList.length > 0) {
        this.trains = currentProject.userList.filter(item => item.roleType === '0').map(item => {
          return {
            label: item.name,
            value: item.id
          };
        });
        this.reviews = currentProject.userList.filter(item => item.roleType === '1').map(item => {
          return {
            label: item.name,
            value: item.id
          };
        });
      }
    },

    queryProject() {
      getProjectList({
          pageNum: 1,
          pageSize: 500,
      }).then(res => {
        if(res.rows && res.rows.length >= 0){
          this.projects = res.rows.map(item => {
            return {
              label: item.name,
              value: item.id,
              userList: item.userList
            }
          })
        }
      })
    },

    queryQuestion(){
      getQuestionList({
        pageNum: 1,
        pageSize: 500,
      }).then(res => {
        if(res.rows && res.rows.length >= 0){
          this.questions = res.rows.map(item => {
            return {
              label: item.title,
              value: item.id,
              type: item.type
            }
          })
        }
      })
    },

    cancel() {
      this.visible = false;
    },
    
    handleClose(tag) {
      this.form.labelList.splice(this.form.labelList.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput?.$refs?.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.labelList.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    showDialog(row) {
      this.reset();
      const isEdit = !!row;
      this.visible = true;
      this.type = isEdit ? "edit" : "new";
      let currentProject = this.projects[0]
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      if (isEdit) {
        this.form = Object.assign(this.form, row);
        currentProject = this.projects.find(item => item.value === this.form.projectId)
      }
      this.updateTrainsAndReviews(currentProject)
      this.title = this.config[this.type].title;
    },

    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.visible = false;
          const data = { ...this.form }

          if(this.type === "new"){
            delete data.id;
          }else if(this.type === 'edit'){
            delete data.questionVo
            delete data.createTime
            delete data.trainUser
            delete data.num
            delete data.reviewUser
          }

          const currentQuestion = this.questions.find(item => item.value === data.questionId)
          data.questionType = currentQuestion?.type || 0

          this.config[this.type]?.func(data).then(() => {
            this.$modal.msgSuccess("提交成功");
            this.visible = false;
            this.$emit("getTableList");
          });
        } else {
          return false;
        }
      });
    },

    reset() {
      this.form = markForm();
      this.$forceUpdate();
    },

  },
};
</script>
<style scoped lang="scss">
.label-list{
  height: 36px;
  display: flex;
  align-items: center;

  .el-tag{
    margin-right: 10px;
  }

  .button-new-tag{
    height: 28px;
    padding: 0 20px;
  }

  .input-new-tag{
    width: 100px;
    height: 28px;
    display: flex;

    ::v-deep .el-input__inner {
      width: 100%;
      height: 100%;
    }
  }
}
.person{
  position: relative;

  .el-icon-user{
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
  }

  .cover{
    width: 100%;
    height: 100%;
    position:absolute;
    top: 0;
    left: 0;
    z-index: 1;
    cursor: pointer;

    &:hover {
      .el-input__inner{
        border-color: #C0C4CC;
      }
    }
  }
}
</style>
